package cn.zzuli.security.security;

import cn.zzuli.utils.utils.R;
import cn.zzuli.utils.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Date: 2021/1/2 18:48
 * @Author: 绯色下午茶
 * @Description:
 */
@Component
public class TokenLogoutHandler implements LogoutHandler {
    private TokenManager tokenManager;
    private RedisTemplate<String,String>redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate<String, String> redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        //从header获取token
        String token = request.getHeader("token");
        if (token != null) {
            tokenManager.removeToken(token);
            String username = tokenManager.getUserInfoFromToken(token);
            redisTemplate.delete(username);
        }
        ResponseUtil.out(response, R.ok());
        //token不为空，移除token，从redis删除token

    }
}
